from flask import Flask, render_template, request, redirect, url_for, session, jsonify
import requests
import os

app = Flask(__name__)
app.secret_key = os.getenv("FLASK_SECRET_KEY", "your-flask-secret-key")

# 后端API地址
API_BASE_URL = os.getenv("API_BASE_URL", "http://localhost:8000")

# 登录页面
@app.route("/", methods=["GET", "POST"])
def login():
    if request.method == "POST":
        username = request.form.get("username")
        password = request.form.get("password")
        
        # 调用后端登录接口
        try:
            response = requests.post(
                f"{API_BASE_URL}/token",
                data={"username": username, "password": password},
                headers={"Content-Type": "application/x-www-form-urlencoded"}
            )
            
            if response.status_code == 200:
                token_data = response.json()
                session["access_token"] = token_data["access_token"]
                session["username"] = username
                return redirect(url_for("index"))
            else:
                return render_template("login.html", error="用户名或密码错误")
        except Exception as e:
            return render_template("login.html", error=f"连接服务器失败: {str(e)}")
    
    # 如果已登录，直接跳转到主页面
    if "access_token" in session:
        return redirect(url_for("index"))
    
    return render_template("login.html")

# 主页面
@app.route("/index", methods=["GET", "POST"])
def index():
    if "access_token" not in session:
        return redirect(url_for("login"))
    
    nodes = []
    error = None
    
    if request.method == "POST":
        query = request.form.get("query", "")
        if query:
            # 调用搜索接口
            try:
                headers = {
                    "Authorization": f"Bearer {session['access_token']}",
                    "Content-Type": "application/json"
                }
                
                response = requests.post(
                    f"{API_BASE_URL}/search-nodes",
                    json={"query": query},
                    headers=headers
                )
                
                if response.status_code == 200:
                    data = response.json()
                    nodes = data.get("nodes", [])
                else:
                    error = f"搜索失败: {response.text}"
            except Exception as e:
                error = f"连接服务器失败: {str(e)}"
    
    return render_template("index.html", nodes=nodes, error=error, username=session.get("username"))

# 更新节点接口
@app.route("/api/update-node", methods=["POST"])
def api_update_node():
    if "access_token" not in session:
        return jsonify({"success": False, "message": "未登录"}), 401
    
    data = request.json
    node_id = data.get("node_id")
    properties = data.get("properties")
    
    if not node_id or not properties:
        return jsonify({"success": False, "message": "参数不完整"}), 400
    
    try:
        headers = {
            "Authorization": f"Bearer {session['access_token']}",
            "Content-Type": "application/json"
        }
        
        response = requests.post(
            f"{API_BASE_URL}/update-node",
            json={"node_id": node_id, "properties": properties},
            headers=headers
        )
        
        return jsonify(response.json()), response.status_code
    except Exception as e:
        return jsonify({"success": False, "message": str(e)}), 500

# 登出
@app.route("/logout")
def logout():
    session.pop("access_token", None)
    session.pop("username", None)
    return redirect(url_for("login"))

if __name__ == "__main__":
    app.run(debug=True, host="0.0.0.0", port=5000)
